package com.dikang.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dikang.yygh.common.exception.YyghException;
import com.dikang.yygh.common.handler.HttpRequestHelper;
import com.dikang.yygh.common.result.ResultCodeEnum;
import com.dikang.yygh.enums.OrderStatusEnum;
import com.dikang.yygh.enums.PaymentStatusEnum;
import com.dikang.yygh.enums.PaymentTypeEnum;
import com.dikang.yygh.model.order.OrderInfo;
import com.dikang.yygh.model.order.PaymentInfo;
import com.dikang.yygh.order.feign.HospitalFeignClient;
import com.dikang.yygh.order.mapper.PaymentInfoMapper;
import com.dikang.yygh.order.service.OrderInfoService;
import com.dikang.yygh.order.service.PaymentService;
import com.dikang.yygh.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentServiceImpl  extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentService  {
    @Autowired
    private OrderInfoService orderService;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Override
    public void savePaymentInfo(OrderInfo order, Integer paymentType) {
        // 查询有没有订单的信息
        QueryWrapper<PaymentInfo> paymentWrapper = new QueryWrapper<>();
        if (order ==null || paymentType ==null){
            throw new YyghException(ResultCodeEnum.SERVICE_ERROR);
        }
        // 查询有没有订单的信息
        paymentWrapper.eq("order_id",order.getId());
        paymentWrapper.eq("payment_type", paymentType);
        Integer count = baseMapper.selectCount(paymentWrapper);
        if (count > 0){return;}
        // 保存交易记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(order.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(order.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(order.getReserveDate()).toString("yyyy-MM-dd")+"|"+order.getHosname()+"|"+order.getDepname()+"|"+order.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(order.getAmount());
        baseMapper.insert(paymentInfo);
    }

    @Override
    public void paySuccess(String outTradeNo, Integer paymentType, Map<String, String> paramMap) {


        // 1根据订单号得到支付记录
        PaymentInfo paymentInfo = this.getPaymentInfoByOutTradeNo(outTradeNo, paymentType);
        if (null == paymentInfo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        if (!paymentInfo.getPaymentStatus().equals(PaymentStatusEnum.UNPAID.getStatus())) {
            return;
        }
        System.out.println("queryPayStatus+++++++>"+paramMap);

        //修改支付状态
        System.out.println("成功支付了");
        PaymentInfo paymentInfoUpd = new PaymentInfo();
        paymentInfoUpd.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfoUpd.setTradeNo(paramMap.get("transaction_id"));
        paymentInfoUpd.setCallbackTime(new Date());
        paymentInfoUpd.setCallbackContent(paramMap.toString());
        this.updatePaymentInfo(outTradeNo, paymentInfoUpd);
        //修改订单状态
        OrderInfo orderInfo = orderService.getById(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderService.updateById(orderInfo);
        // 向医院接口，更新订单支付信息
        SignInfoVo signInfoVo
                = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(null == signInfoVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updatePayStatus");
        if(result.getInteger("code") != 200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
    }

    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("payment_type", paymentType);
        return baseMapper.selectOne(queryWrapper);
    }

    private void updatePaymentInfo(String outTradeNo, PaymentInfo paymentInfoUpd) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no", outTradeNo);
        baseMapper.update(paymentInfoUpd, queryWrapper);
    }

    private PaymentInfo getPaymentInfoByOutTradeNo(String outTradeNo,Integer paymentType){
        QueryWrapper<PaymentInfo> paymentWrapper = new QueryWrapper<>();
        paymentWrapper.eq("out_trade_no",outTradeNo);
        paymentWrapper.eq("payment_type", paymentType);
        PaymentInfo paymentInfo = baseMapper.selectOne(paymentWrapper);
        return paymentInfo;
    }
}
